package com.huangmb.anymark.app.api;

import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;
import com.android.volley.toolbox.Volley;
import com.huangmb.androidlib.utils.ToastUtils;
import com.huangmb.anymark.app.app.AnyMarkApplication;
import com.huangmb.anymark.app.net.HttpRequest;
import com.huangmb.anymark.app.net.RequestManager;
import com.huangmb.anymark.app.net.RequestParameter;
import com.huangmb.anymark.app.net.Response;
import com.huangmb.androidlib.utils.Logger;
import org.jsoup.Connection;

import java.net.CookieStore;
import java.util.List;
import java.util.Map;

/**
 * API的基类
 *
 * @author hmb
 * @version 1.0
 * @since 2016/4/17 15:30
 */
public class BaseApi implements com.android.volley.Response.Listener<String> {

    private static final String TAG = "BaseApi";
    private static final Handler handler = new Handler();
    //protected static final String API_SERVER = "http://192.168.191.1:8080/anymark";
    protected static final String API_SERVER = "http://115.159.107.159:8080/anymark";

    protected static void execute(String url, Connection.Method method, Map<String, String> params, final Listener listener) {
        HttpRequest httpRequest = new HttpRequest(url, method, params, new HttpRequest.Callback() {
            @Override
            public void onHttpResponse(String content) {
                if (listener == null) {
                    return;
                }
                if (listener.onRawData(content)) {
                    return;
                }
                Response response = Response.parse(content);
                if (response == null) {
                    Logger.d(TAG, "Json 解析异常");
                    notifyOnFail(listener, ErrorCode.PARSE_ERROR, "数据解析错误");
                } else if (response.hasError()) {
                    notifyOnFail(listener, response.getErrorCode(), response.getErrorMessage());
                } else {

                    notifyOnSuccess(listener, response.getResult());
                }
            }

            @Override
            public void onNetworkError(String msg) {
                notifyOnFail(listener, ErrorCode.NETWORK_ERROR, msg);
            }
        });
        RequestManager.getInstance().addTask(httpRequest);
    }

    private static void notifyOnFail(final Listener listener, final int code, final String msg) {
        if (listener == null ) {
            return;
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                listener.onFail(code, msg);
            }
        });
    }

    private static void notifyOnSuccess(final Listener listener, final String content) {
        if (listener == null) {
            return;
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                listener.onSuccess(content);
            }
        });
    }

    protected static void clearCookie() {
        CookieStore cookieStore = RequestManager.getInstance().getCookieManager().getCookieStore();
        if (cookieStore != null) {
            cookieStore.removeAll();
        }
    }

    @Override
    public void onResponse(String response) {

    }

    public interface Listener {
        /**
         * 原始数据
         *
         * @param data 原始数据
         * @return true 停止解析数据，onSuccess方法将不会执行 false将继续执行解析程序，解析得到返回数据中的result字段内容
         */
        boolean onRawData(String data);

        /**
         * 当返回数据合法时，即errorcode为0时
         *
         * @param result 返回数据中的result字段内容
         */
        void onSuccess(String result);

        /**
         * 当返回数据非法时，即errorcode不为0时。
         *
         * @param errorCode    错误码，负数为本地错误，正数为服务器返回的错误码
         * @param errorMessage 错误提示
         */
        void onFail(int errorCode, String errorMessage);

    }

    public static class AbsListener implements Listener {
        private ProgressBar mProgressBar;
        public AbsListener(){}
        public AbsListener(ProgressBar progressBar){
            this.mProgressBar = progressBar;
        }
        @Override
        public boolean onRawData(String result) {
            return false;
        }

        @Override
        public void onFail(int errorCode, String errorMessage) {
            if (errorCode == ErrorCode.NETWORK_ERROR){
                ToastUtils.showShort(AnyMarkApplication.getInstance(),"网络异常");
            }
            if(mProgressBar != null){
                mProgressBar.setVisibility(View.GONE);
            }
        }

        @Override
        public void onSuccess(String result) {
            if(mProgressBar != null){
                mProgressBar.setVisibility(View.GONE);
            }
            Logger.d("BaseApi", result);
        }
    }
}
